// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskForm = document.getElementById('task-form');
    const taskInput = document.getElementById('task-input');
    const tasksContainer = document.getElementById('tasks-container');
    const filterButtons = document.querySelectorAll('.filter-btn');
    
    // 从本地存储加载任务
    let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
    let currentFilter = 'all';
    
    // 初始化应用
    function init() {
        renderTasks();
        setupEventListeners();
    }
    
    // 设置事件监听器
    function setupEventListeners() {
        // 添加任务表单提交事件
        taskForm.addEventListener('submit', function(e) {
            e.preventDefault();
            addTask();
        });
        
        // 筛选按钮点击事件
        filterButtons.forEach(button => {
            button.addEventListener('click', function() {
                // 更新活动按钮
                filterButtons.forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');
                
                // 更新筛选条件并重新渲染
                currentFilter = this.dataset.filter;
                renderTasks();
            });
        });
    }
    
    // 添加新任务
    function addTask() {
        const taskText = taskInput.value.trim();
        
        if (taskText === '') {
            alert('请输入任务内容');
            return;
        }
        
        const newTask = {
            id: Date.now(),
            text: taskText,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        saveTasks();
        renderTasks();
        
        // 清空输入框
        taskInput.value = '';
    }
    
    // 切换任务完成状态
    function toggleTaskCompletion(taskId) {
        tasks = tasks.map(task => {
            if (task.id === taskId) {
                return { ...task, completed: !task.completed };
            }
            return task;
        });
        
        saveTasks();
        renderTasks();
    }
    
    // 编辑任务
    function editTask(taskId) {
        const task = tasks.find(t => t.id === taskId);
        const newText = prompt('编辑任务:', task.text);
        
        if (newText !== null && newText.trim() !== '') {
            tasks = tasks.map(t => {
                if (t.id === taskId) {
                    return { ...t, text: newText.trim() };
                }
                return t;
            });
            
            saveTasks();
            renderTasks();
        }
    }
    
    // 删除任务
    function deleteTask(taskId) {
        if (confirm('确定要删除这个任务吗？')) {
            tasks = tasks.filter(task => task.id !== taskId);
            saveTasks();
            renderTasks();
        }
    }
    
    // 保存任务到本地存储
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 渲染任务列表
    function renderTasks() {
        // 根据筛选条件过滤任务
        let filteredTasks = tasks;
        
        if (currentFilter === 'pending') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 清空容器
        tasksContainer.innerHTML = '';
        
        // 如果没有任务，显示提示信息
        if (filteredTasks.length === 0) {
            const emptyMessage = document.createElement('div');
            emptyMessage.className = 'empty-message';
            
            if (currentFilter === 'all') {
                emptyMessage.textContent = '还没有任务，添加一个吧！';
            } else if (currentFilter === 'pending') {
                emptyMessage.textContent = '没有待完成的任务';
            } else if (currentFilter === 'completed') {
                emptyMessage.textContent = '没有已完成的任务';
            }
            
            tasksContainer.appendChild(emptyMessage);
            return;
        }
        
        // 渲染每个任务
        filteredTasks.forEach(task => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-item ${task.completed ? 'completed' : ''}`;
            taskElement.dataset.id = task.id;
            
            taskElement.innerHTML = `
                <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
                <span class="task-text">${task.text}</span>
                <div class="task-actions">
                    <button class="edit-btn">编辑</button>
                    <button class="delete-btn">删除</button>
                </div>
            `;
            
            // 添加事件监听器
            const checkbox = taskElement.querySelector('.task-checkbox');
            const editBtn = taskElement.querySelector('.edit-btn');
            const deleteBtn = taskElement.querySelector('.delete-btn');
            
            checkbox.addEventListener('change', () => toggleTaskCompletion(task.id));
            editBtn.addEventListener('click', () => editTask(task.id));
            deleteBtn.addEventListener('click', () => deleteTask(task.id));
            
            tasksContainer.appendChild(taskElement);
        });
    }
    
    // 初始化应用
    init();
});